import React, { PureComponent } from "react";
import { Card, Divider, Popconfirm, Spin, Table } from "antd"; // Tooltip
import { connect } from "dva";
import { Link } from "react-router-dom";
import queryString from "query-string";
import dynamic from "umi/dynamic";
// import cn from "classnames";
import styles from "./index.less";

import CardTitle from "./components/CardTitle";
// import Catalogue from "../../../components/catalogue/Catalogue";
import PageLayout from "../../../components/pageconlayout/PageLayout";
import {
  getMenuRouter,
  getPageOperate,
} from "../../../components/layouts/menuFn";

import { openNotificationWithIcon, delay } from "../../../utils/comm";

// const TableList = dynamic({ loader: async () => {
//   await delay(800);
//   return import("../../../components/tablelist/TableList");
// } });
// const QueryExtra = dynamic({ loader: async () => {
//   await delay(500);
//   return import("./components/QueryExtra");
// } });
const CreateFlow = dynamic({ loader: async () => {
  await delay(1000);
  return import("./components/CreateFlow");
},
});
const ImportFlow = dynamic({ loader: async () => {
  await delay(1000);
  return import("./components/ImportFlow");
} });
const Catalogue = dynamic({ loader: async () => {
  await delay(100);
  return import("../../../components/catalogue/Catalogue");
} });
const AdvancedFilter = dynamic({ loader: async () => {
  await delay(1000);
  return import("./components/AdvancedFilter");
} });

const TYPEMAP = {
  tenant: 1,
  app: 2,
  business: 3,
};

const disabledDelProps = {
  title: '已部署流程不能删除',
  style: {
    color: '#999',
    cursor: 'not-allowed',
  },
}

@connect(({ FlowConfigure, appListMenu, loading, Public }) => ({
  flowConfigStore: FlowConfigure,
  loading,
  menuAppStore: appListMenu,
  focusApp: appListMenu.focusApp,
  menuDataList: Public.menuDataList,
  resourceList: Public.resourceList,
}))
class FlowConfigure extends PureComponent {
  constructor(props) {
    super(props);
    this.openNotificationWithIcon = openNotificationWithIcon;
    this.getMenuRouter = getMenuRouter.bind(this);
    this.getPageOperate = getPageOperate.bind(this);
    this.state = {
      page: {
        pageNum: 1,
        pageSize: 6,
      },
      selectedKeys: [],
      visible: false,
      importVisible: false,
      filterVisible: false,
      route: [],
    };
    this.baseQueryParam = {
      appId: "",
      busiId: "",
      tenantId: "",
      searchKey: "",
      timeStart: "", // 开始时间
      timeEnd: "", // 结束时间
      lastVersion : 1,
    };
    this.queryParams = this.baseQueryParam;
    this.columns = [
      {
        title: "流程模型名称",
        align: 'center',
        dataIndex: "modelName",
        key: "modelName",
        width: '60px',
        render: (text, record) => {
          return (
            <div>
              <span
                title={text}
              >
                <a
                  style={{ whiteSpace: 'pre' }}
                  href={`${window.location.origin}${
                  window.routerBase || "/"
                }flowmanage/flowconfigure/detail?modelid=${record.modelId}`}
                  target="_blank"
                  rel="noopener noreferrer"
                >
                  {text}
                </a>
              </span>
              {/* {record.category && this.getStatus(record.category)} */}
            </div>
          );
        },
      },
      {
        title: "流程模型编码",
        align: 'center',
        dataIndex: "modelKey",
        key: "modelKey",
        width: '60px',
        render: (v) => {
          return (
            <span
              title={v}
            >
              {v}
            </span>
          );
        },
      },
      {
        title: "版本号",
        align: 'center',
        dataIndex: "version",
        key: "version",
        width: '35px',
      },
      {
        title: "查看版本",
        align: 'center',
        width: '45px',
        dataIndex: "viewVersion",
        key: "viewVersion",
        render: (text, record) => {
          return (
            <div>
              <Link
                to={{
                  pathname: "/flowmanage/flowconfigure/versionmanage",
                  search: queryString.stringify({
                    modelKey: record.modelKey,
                  }),
                }}
              >
                版本历史
              </Link>
            </div>
          );
        },
      },
      {
        title: "所属应用",
        align: 'center',
        dataIndex: "appName",
        key: "appName",
        width: '45px',
        render: (v) => {
          return (
            <span
              title={v}
            >
              {v}
            </span>
          );
        },
      },
      {
        title: "状态",
        align: 'center',
        dataIndex: "category",
        key: "category",
        width: '30px',
        render: (text, record) => {
         return record.category && this.getStatus(record.category)
        },
      },
      {
        title: "创建人",
        align: 'center',
        dataIndex: "creatorName",
        key: "creatorName",
        width: '50px',
        render: (v) => {
          return (
            <span
              title={v}
            >
              {v}
            </span>
          );
        },
      },
      {
        title: "创建时间",
        align: 'center',
        dataIndex: "createTime",
        key: "createTime",
        width: '80px',
        render: (v) => {
          return (
            <span
              title={v}
            >
              {v}
            </span>
          );
        },
      },
      {
        title: "修改人",
        align: 'center',
        dataIndex: "creatorName",
        key: "updateName",
        width: '50px',
        render: (v) => {
          return (
            <span
              title={v}
            >
              {v}
            </span>
          );
        },
      },
      {
        title: "修改时间",
        align: 'center',
        dataIndex: "lastUpdateTime",
        key: "lastUpdateTime",
        width: '80px',
        render: (v) => {
          return (
            <span
              title={v}
            >
              {v}
            </span>
          );
        },
      },
      {
        title: "操作",
        align: 'center',
        width: '150px',
        dataIndex: "opration",
        render: (text, record) => {
          const deploy = this.getOprateDisable("deploy");
          const del = this.getOprateDisable("delete");
          const edit = this.getOprateDisable("edit");
          const copy = this.getOprateDisable("copy");

          return (
            <div>
              {copy && (
                <React.Fragment>
                  <a
                    onClick={(e) => {
                      e.preventDefault();
                      this.handleCreateVisible(true, record);
                    }}
                  >
                    复制
                  </a>
                  <Divider type="vertical" />
                </React.Fragment>
              )}
              {record.category === 'RUNNING' && (
                <React.Fragment>
                  <Popconfirm
                    placement="left"
                    title={`确定下线流程：${record.modelName}?`}
                    onConfirm={() => {
                      this.handleOffline(record);
                    }}
                    okText="确定"
                    cancelText="取消"
                  >
                    <a
                      onClick={(e) => {
                        e.preventDefault();
                      }}
                    >
                      下线
                    </a>
                  </Popconfirm>
                  <Divider type="vertical" />
                </React.Fragment>
              )}
              {record.category !== "RUNNING" && deploy && (
                <React.Fragment>
                  <Popconfirm
                    placement="left"
                    title={`确定部署流程：${record.modelName}?`}
                    onConfirm={() => {
                      this.handleDeploy(record);
                    }}
                    okText="确定"
                    cancelText="取消"
                  >
                    <a
                      onClick={(e) => {
                        e.preventDefault();
                      }}
                    >
                      部署
                    </a>
                  </Popconfirm>
                  <Divider type="vertical" />
                </React.Fragment>
              )}
              {/* {record.category === "RUNNING" && (
              <React.Fragment>
                {
                  record.isUsed ? (
                    <Popconfirm
                      placement="left"
                      title={`确定撤回流程：${record.modelName}?`}
                      onConfirm={() => {
                        // this.handleDeploy(record);
                      }}
                      okText="确定"
                      cancelText="取消"
                    >
                      <a onClick={(e) => {
                        e.preventDefault();
                      }}
                      >
                        撤回
                      </a>
                    </Popconfirm>
                  ) : (
                    <Tooltip title="流程被使用，不能撤回">
                      <span style={{ color: '#999' }}>撤回</span>
                    </Tooltip>
                  )
                }
                <Divider type="vertical" />
              </React.Fragment>
            )} */}
              {edit && (
                <React.Fragment>
                  <Link
                    to={{
                      pathname: "/flowmanage/flowchart",
                      search: queryString.stringify({
                        modelId: record.modelId,
                        modelStatus: record.modelStatus,
                      }),
                    }}
                  >
                    编辑
                  </Link>
                  <Divider type="vertical" />
                </React.Fragment>
              )}
              <Link
                to={{
                  pathname: "/flowmanage/flowconfigure/chartview",
                  search: queryString.stringify({
                    modelid: record.modelId,
                  }),
                }}
              >
                查看流程图
              </Link>
              {del && (
                <React.Fragment>
                  <Divider type="vertical" />
                  { record.category !== "RUNNING" ? (
                    <Popconfirm
                      placement="left"
                      title={`确定删除流程：${record.modelName}?`}
                      onConfirm={() => {
                        this.handleDel(record);
                      }}
                      okText="确定"
                      cancelText="取消"
                    >
                      <a
                        onClick={(e) => {
                          e.preventDefault();
                        }}
                      >
                        删除
                      </a>
                    </Popconfirm>
                  ) : (
                    <a
                      onClick={(e) => {
                        e.preventDefault();
                      }}
                      {...disabledDelProps}
                    >
                      删除
                    </a>
                  )}
                </React.Fragment>
              )}
            </div>
          );
        },
      },
      {
        title: "",
        align: 'center',
        width: '5%',
        dataIndex: "import",
        key: "import",
        render: (text, record) => {
          return (
            <a
              onClick={() => {
            this.handleExport(record);
          }}
            >
              导出
            </a>
)
        },
      },
    ];
  }

  componentDidMount() {
    this.isLeaf = false;
    this.initAppListData();
    this.initData();
  }

  componentDidUpdate(preProps) {
    const { focusApp } = this.props;
    const { focusApp: preFocusApp } = preProps;
    if (preFocusApp.id && `${preFocusApp.id || 0}` !== `${focusApp.id || 0}`) {
      // 应用切换更新页面数据
      this.initAppListData();
      this.resetPageData();
    }
  }

  componentWillUnmount() {
    this.isLeaf = true;
    const { dispatch } = this.props;
    dispatch({ type: "FlowConfigure/clearData" });
  }

  getStatus = (status) => {
    switch (status) {
      case "HISTORY":
        return (
          // <span className={cn(styles.status, styles.statusGrey)}>停用</span>
          <span>停用</span>
        );
      case "RUNNING":
        return (
          // <span className={cn(styles.status, styles.statusGreen)}>在线</span>
          <span>在线</span>
        );
      case "DESIGN":
        return (
          // <span className={cn(styles.status, styles.statusBlue)}>未发布</span>
          <span>未发布</span>
        );
      default:
        break;
    }
  };

  // 加载应用数据
  initAppListData = () => {
    const { dispatch } = this.props;
    dispatch({ type: "appListMenu/getAppListData" });
  };

  // 重置页面数据
  resetPageData = () => {
    const { dispatch } = this.props;
    this.queryParams = this.baseQueryParam;
    dispatch({ type: "FlowConfigure/clearData" });
    this.setState({
      page: { pageNum: 1, pageSize: 6 },
      filterVisible: false,
      selectedKeys: [],
    });
    if (this.QueryExtra) this.QueryExtra.handleReset();
    if (this.AdvancedFilter) this.AdvancedFilter.handleReset();
  };

  getOprateDisable = (type) => {
    const {
      location: { pathname = "" },
      menuDataList,
      resourceList,
    } = this.props;
    const res = this.getPageOperate(type, pathname, menuDataList, resourceList);
    return res;
  };

  // 获取查询条件组件的this
  getRef = (type, _this) => {
    this[type] = _this;
  };

  // 获取查询参数
  getQueryParam = () => {
    const {
      page: { pageNum, pageSize },
    } = this.state;
    return { ...this.queryParams, pageNum, pageSize };
  };

  // 查询条件改变
  handleParamsChange = (item = {}) => {
    if(item.lastVersion === 0){
      delete this.queryParams.category
    }
    this.queryParams = { ...this.queryParams, ...item };
  };

  // 触发查询
  initData = () => {
    const { dispatch } = this.props;
    const params = this.getQueryParam();
    // console.log(params)
    // if (!params.appId && !params.busiId && !params.tenantId) return;
    dispatch({ type: "FlowConfigure/getFlowListData", payload: params });
  };

  // 页码页数改变
  // handlePageChange = (pageNum, pageSize) => {
  //   this.setState({ page: { pageNum, pageSize } }, () => {
  //     this.initData();
  //   });
  // };

  handlePageChange = ({ current: pageNum, pageSize }) => {
    this.setState({ page: { pageNum, pageSize } }, () => {
      this.initData();
    });
  };

  // 搜索
  handleSearch = () => {
    const { page } = this.state;
    this.setState({ page: { ...page, pageNum: 1 } }, () => {
      this.initData();
    });
  };

  // 左侧应用选择
  handleTreeNodeSelect = (data, e, preId, nomalSelectedKeys) => {
    const Keys = data[0].split("|");

    const newSelectkeys = nomalSelectedKeys || data;
    const queryParams = { ...this.queryParams };
    // console.log(queryParams)
    if (!(data && data[0].length > 0)) return;
    if (e.node.props.isLeaf) {
      // 子节点
      this.queryParams = {
        ...queryParams,
        busiId: data[0],
        appId: "",
        tenantId: "",
      };
    } else if (Keys[0] === "tenant") {
      this.queryParams = {
        ...queryParams,
        tenantId: Keys[Keys.length - 1],
        busiId: "",
        appId: "",
      };
    } else {
      this.queryParams = {
        ...queryParams,
        appId: Keys[Keys.length - 1],
        busiId: "",
        tenantId: "",
      };
    }
    this.setState({ selectedKeys: newSelectkeys });
    this.handleSearch();
  };

  // 查询父节点路径
  findIndexArray = (data, id, indexArray, level) => {
    const arr = Array.from(indexArray);
    for (let i = 0, len = data.length; i < len; i += 1) {
      arr.push(data[i].id);
      if (data[i].id === Number(id) && arr.length === level) {
        return arr;
      }

      const { apps, busi } = data[i];
      const children = apps || busi;
      if (children && children.length) {
        const result = this.findIndexArray(children, id, arr, level);
        if (result) {
          return result;
        }
      }
      arr.pop();
    }
    return false;
  };

  // 创建流程弹窗
  handleCreateVisible = (visible, record) => {
    const { menuAppStore } = this.props;
    const { appListMenuData = [] } = menuAppStore;
    const { selectedKeys } = this.state;
    let route = [];

    if (selectedKeys[0]) {
      const Keys = selectedKeys[0].split("|");
      route = this.findIndexArray(
        appListMenuData,
        Keys[Keys.length - 1],
        [],
        TYPEMAP[Keys[0]],
      ); // 选中节点的父节点，0：租户，1：应用，2：业务
    }

    this.record = record;
    if (this.isLeaf) return;
    this.setState({ visible, route });
  };

   // 导入流程弹窗
   handleImportVisible = (importVisible, record) => {
    const { menuAppStore } = this.props;
    const { appListMenuData = [] } = menuAppStore;
    const { selectedKeys } = this.state;
    let route = [];

    if (selectedKeys[0]) {
      const Keys = selectedKeys[0].split("|");
      route = this.findIndexArray(
        appListMenuData,
        Keys[Keys.length - 1],
        [],
        TYPEMAP[Keys[0]],
      ); // 选中节点的父节点，0：租户，1：应用，2：业务
    }

    this.record = record;
    if (this.isLeaf) return;
    this.setState({ importVisible, route });
   };

  // 导出
  handleExport = (record = {}) => {
    const { modelId } = record;
    if (!modelId) return;
    const url = `${window.location.origin}/flow-platform/model/download/json?modelId=${modelId}`;
    window.location.href = url;
  }

  // 删除
  handleDel = (record = {}) => {
    const { dispatch } = this.props;
    const { modelId } = record;
    if (!modelId) return;
    dispatch({
      type: "FlowConfigure/delFlow",
      payload: { modelId },
    }).then(({ errCode, errMsg }) => {
      if (errCode === 0) {
        this.openNotificationWithIcon("success", "", "删除成功");
        this.handleSearch();
      } else {
        this.openNotificationWithIcon("error", "", errMsg || "删除失败");
      }
    });
  };

  // 部署
  handleDeploy = (record = {}) => {
    const { modelId } = record;
    if (!modelId) return;
    const { dispatch } = this.props;
    dispatch({
      type: "FlowConfigure/processDeploy",
      payload: { modelId },
    }).then(({ errCode, errMsg }) => {
      if (errCode === 0) {
        this.openNotificationWithIcon("success", "", "部署成功");
        this.handleSearch();
      } else {
        this.openNotificationWithIcon("error", "", errMsg || "部署失败");
      }
    });
  };

   // 下线
   handleOffline = (record = {}) => {
    const { modelId } = record;
    if (!modelId) return;
    const { dispatch } = this.props;
    dispatch({
      type: "FlowConfigure/processOffline",
      payload: { modelId },
    }).then(({ success, errMsg }) => {
      if (success === true) {
        this.openNotificationWithIcon("success", "", "下线成功");
        this.handleSearch();
      } else {
        this.openNotificationWithIcon("error", "", errMsg || "下线失败");
      }
    });
  };

  handleFilterVisible = () => {
    const { filterVisible } = this.state;
    this.setState({ filterVisible: !filterVisible });
  };

  render() {
    const { flowConfigStore, menuAppStore, loading, dispatch } = this.props;
    const {
      page: { pageNum, pageSize },
      visible,
      importVisible,
      // filterVisible,
      selectedKeys,
      route,
    } = this.state;
    const { flowListData = [], totalCount = 0 } = flowConfigStore;
    const {
      appListMenuData = [],
      appListAll = [],
      appBusinessObjAll = [],
    } = menuAppStore;

    const listLoading =
      loading.effects["FlowConfigure/getFlowListData"] || false;
    const createLoading =
      loading.effects["FlowConfigure/addOrCopyFlow"] || false;
    const deployLoading =
      loading.effects["FlowConfigure/processDeploy"] || false;
    const deleteLoading = loading.effects["FlowConfigure/delFlow"] || false;
    const menuListLoading =
      loading.effects["appListMenu/getAppListData"] || false;
    return (
      <div className={styles.root}>
        <PageLayout
          leftContent={
            <Card
              title="流程模型分类"
              style={{
                width: "100%",
                height: "100%",
                minHeight: window.innerHeight - 64 - 16 - 16 - 104,
              }}
            >
              <Spin spinning={menuListLoading} delay={300}>
                <Catalogue
                  CatalogueData={appListMenuData}
                  treeNodeSelect={this.handleTreeNodeSelect}
                  selectedKeys={selectedKeys}
                />
              </Spin>
            </Card>
          }
          rightContent={
            <Spin spinning={deployLoading || deleteLoading} delay={300}>
              <Card
                title={
                  <CardTitle
                    total={totalCount}
                    handleCreateVisible={this.handleCreateVisible}
                    handleImportVisible={this.handleImportVisible}
                    addVisible={this.getOprateDisable("add")}
                  />
                }
                // extra={
                //   <QueryExtra
                //     onChange={this.handleParamsChange}
                //     onSearch={this.handleSearch}
                //     visible={filterVisible}
                //     handleFilterVisible={this.handleFilterVisible}
                //     getRef={(_this) => this.getRef("QueryExtra", _this)}
                //   />
                // }
                bodyStyle={{
                  minHeight: window.innerHeight - 64 - 16 - 16 - 48 - 104,
                }}
                style={{ width: "100%" }}
              >
                <AdvancedFilter
                  handleSearch={this.handleSearch}
                  handleParamsChange={this.handleParamsChange}
                  visible
                  getRef={(_this) => this.getRef("AdvancedFilter", _this)}
                />
                {/* <TableList
                  dataSource={flowListData}
                  loading={listLoading}
                  columns={this.columns}
                  titleName="modelName"
                  operationName="opration"
                  onPageChange={this.handlePageChange}
                  rowKey="modelId"
                  className={styles.listcon}
                  pagination={{
                    showQuickJumper: true,
                    showSizeChanger: true,
                    pageSizeOptions: ["6", "10", "20", "30"],
                    current: pageNum,
                    pageSize,
                    total: totalCount,
                  }}
                /> */}
                <Table
                  dataSource={flowListData}
                  loading={listLoading}
                  columns={this.columns}
                  scroll={{x: 1200}}
                  rowKey="modelId"
                  bordered
                  className={styles.spacing}
                  onChange={this.handlePageChange}
                  pagination={{
                    showQuickJumper: true,
                    showSizeChanger: true,
                    pageSizeOptions: ["6", "10", "20", "30"],
                    current: pageNum,
                    pageSize,
                    total: totalCount,
                  }}
                />
              </Card>
            </Spin>
          }
          rightClassName={styles.right_over}
        />
        <CreateFlow
          visible={visible}
          handleCreateVisible={this.handleCreateVisible}
          dispatch={dispatch}
          confirmLoading={createLoading}
          appList={appListAll}
          appBusinessObj={appBusinessObjAll}
          data={this.record}
          route={route} // 选中节点的路径节点数据
        />
        <ImportFlow
          visible={importVisible}
          handleImportVisible={this.handleImportVisible}
          dispatch={dispatch}
          confirmLoading={createLoading}
          appList={appListAll}
          appBusinessObj={appBusinessObjAll}
          data={this.record}
          route={route}
        />
      </div>
    );
  }
}

export default FlowConfigure;
